

import permision from "@/common/permission.js";
import store from '../store'
module.exports = {
	wsHost: 'ws://34.217.18.254:9502',
	BASE_URL: 'http://47.74.30.152:3500/api/',
	queryString: function(json) {
		if (!json) return ''
		return this.cleanArray(Object.keys(json).map(key => {
			if (json[key] === undefined) return ''
			return key + '=' + json[key]
		})).join('&')
	},
	goBack: function() {
		uni.navigateBack();
	},
	// 去启动页
	goStartPage: function() {
		uni.redirectTo({
			url: "../get_address/index"
		})
	},
	showLoading(state) {
		if (state) {
			uni.showLoading({
			   mask: true,
			   success: () => {
				   
			   }
			});
		} else {
			uni.hideLoading({
			   mask: true,
			   success: () => {
				   
			   }
			});
		}
	},
	getUserInfo() {
		let userInfo = uni.getStorageSync('userInfo');
		if (!userInfo) {
			userInfo = {}
		}
		return userInfo
	},
	setUserInfo(userInfo) {
		uni.setStorageSync('userInfo', userInfo)
	},
	// setHistoricalAccessAddress(pageData) {
	// 	// [{ addr_name, addr },{}]
	// 	let data = this.getHistoricalAccessAddress()
	// 	if (data.length >= 10) {
	// 		data.slice(9)
	// 	}
	// 	data.unshift(pageData)
	// 	uni.setStorageSync('historical_access_address', data)
	// },
	// getHistoricalAccessAddress() {
	// 	let data = uni.getStorageSync('historical_access_address')
	// 	if (data) {
	// 		if (data.length > 10) {
	// 			return data.slice(0, 9)
	// 		}
	// 		return data
	// 	}
	// 	return []
	// },
	tips (title) {
		uni.showToast({
			title,
			icon: 'none'
		})
  },
   copy (value) {
    uni.setClipboardData({
        data: value,
        success: function () {
          uni.showToast({
            title: '复制成功!',
            icon: 'none'
          })
        }
    });
  },
	getToken: function() {
    let userInfo = uni.getStorageSync('userInfo');
		if (userInfo) {
			return userInfo.token
		}
		return '';
	},
	fromapp: function() {
		//var $paltform= uni.platform();
		return 'uniapp';
	},
	// 上传文件
	uploadFileSync({ftype}) {
		return new Promise( (resolve, reject) => {
			const {  user_id, token } = this.getUserInfo()
			uni.chooseImage({
				count: 1,
			    success: (chooseImageRes) => {
			        const tempFilePaths = chooseImageRes.tempFilePaths;
					const tempFiles = chooseImageRes.tempFiles
			        uni.uploadFile({
			            url: this.BASE_URL + 'public/uploadfile', // 仅为示例，非真实的接口地址
			            filePath: tempFilePaths[0],
						name: 'file',
						formData: {
							token,
							user_id,
							'ftype': ftype
						},
			            success: (res) => {
							resolve(JSON.parse(res.data))
			            }
			        });
			    }
			});
		})
	},
	getSync(ops, isCheckToken = true) {
		if (isCheckToken) {
			ops = this.generateOptions(ops)
		}
		let url = ops.url
		const reg = /(http|https):\/\/([\w.]+\/?)\S*/ig
		if (!url.match(reg)) {
			url = this.BASE_URL + ops.url
		}
		return new Promise((resolve, reject) => {
			uni.request({
				url,
				data: ops.data,
				method: 'GET',
				success: (rs) => {
					if (!ops.url.match(reg)) {
						this.toSuccess(rs, resolve)
					} else {
						resolve(rs)
					}
				},
				fail: (err) => {
					// uni.navigateTo({
					// 	url: '/pages/error/index?type=1'
					// })
				}
			});
		})
	
	},
	 /**
	 * 字符串隐藏部分变**
	 * @param {*} str 需要隐藏的字符串
	 * @param {*} frontLen 头部明文长度
	 * @param {*} endLen  尾部明文长度
	 */
	plusXing(str, frontLen, endLen) {
		var len = str.length - frontLen - endLen
		var xing = ''
		for (var i = 0; i < len; i++) {
			xing += '*'
		}
		return str.substring(0, frontLen) + '...' + str.substring(str.length - endLen)
	},
	post: function(ops, callback) {
		ops = this.generateOptions(ops)
		if (!ops) return ops
		uni.request({
			url: this.BASE_URL + ops.url,
			data: ops.data,
			method: 'POST',
			header: {
				'content-type': 'application/x-www-form-urlencoded',
				// 'Authorization': 'Bearer' + this.basic_token,
			},
			success: rs => {
        if (rs.data.code == 2 && 'Token'.indexOf(rs.data.msg) > -1) {
          this.setUserInfo('')
          uni.reLaunch({
            url: "/pages/login/index"
          })
        } else {
          if (!store.state.isLogin) {
            store.commit('changeLogin', true)
          }
          callback && callback(rs.data)
        }
				
			},
			fail: (err) => {
			}
		});
	},
	postSync(ops, callback) {
		ops = this.generateOptions(ops)
		// console.log(ops.data)
		return new Promise((resolve, reject) => {
			uni.request({
				url: this.BASE_URL + ops.url,
				data: ops.data,
				method: 'POST',
				header: {
					'content-type': 'application/x-www-form-urlencoded',
				},
				success: (rs) => {
					// console.log(rs)
          this.toSuccess(rs, resolve)
          
				},
				fail: (err) => {
					// uni.navigateTo({
					// 	url: '/pages/error/index?type=1'
					// })
				}
			});
		})

	},
	generateOptions(ops) {
    const isBeforeLoginApi = ops.isBeforeLoginApi || false
		if (!this.isLogin() && !isBeforeLoginApi) {

			uni.showToast({
				icon: 'none',
				title: '请先登录',
				success: () => {
          // this.changeLogin(false)
					this.goLogin()
				}
			})
		}
		ops.data.token = this.getToken()
		ops.data.userid = this.getUserInfo().user_id
		return ops
	},
	toSuccess(rs, resolve, success) {
		if ([1000001, 1000002, 1000004, 1000005, 1010000, 1010010].includes(rs.data.code)) {
			uni.showToast({
				icon: 'none',
				title: rs.data.msg,
				success: () => {
					this.logOut(() => {
						uni.reLaunch({
							url: '../login/index',
						});
					})
					
				}
			})
		}  else if (rs.data.code == 1000043) {
			uni.showToast({
				icon: 'none',
				title: rs.data.msg,
				success: () => {
					this.goHome()
				}
			})
		}
		else if (rs.data.code == 1000042) {
			uni.showToast({
				title: rs.data.msg + '请充值',
				icon: 'none'
			});
		}
		 else if (rs.data.code != 0) {
			uni.showToast({
				title: rs.data.msg || 'error',
				icon: 'none',
				success: () => {
					uni.navigateTo({
						url: '/pages/error/index?type=1'
					})
				}
			});
		} else {
			// callback
			if (resolve) {
				return resolve(rs.data)
			} else {
				success(rs.data);
			}

		}
	},
	logOut(callback) {
		uni.setStorageSync('userInfo', {})
		callback()
	},
	isLogin: function() {
		if (this.getToken()) {
      // 启动心跳
			return true
		}
		return false
	},
	goHome: function(pageData) {
		uni.reLaunch({
      url: '/pages/index/index?' + this.queryString(pageData)
    });
	},
	
	goLogin: function() {
		uni.reLaunch({
			url: '/pages/login/index',
		});
	},
	getCurPage() {
		let pages = getCurrentPages();
		// #ifdef MP-WEIXIN  
		return pages[pages.length - 1].$vm;
		// #endif  
		return pages[pages.length - 1];
	},

	
	// 检查系统设置
	async checkPermission() {
	    let status = permision.isIOS ? await permision.requestIOS('location') :
	        await permision.requestAndroid('android.permission.ACCESS_FINE_LOCATION');
	    if (status === null || status === 1) {
	        status = 1;
	    } else if (status === 2) {
	        uni.showModal({
	            content: "系统定位已关闭",
	            confirmText: "确定",
	            showCancel: false,
	            success: function(res) {
	            }
	        })
	    } else if (status.code) {
	        uni.showModal({
	            content: status.message
	        })
	    } 
	
	    return status;
	},

	openSetting() {
		// 打开小程序的设置
		// #ifdef MP-WEIXIN
		uni.openSetting();
		// #endif
		// App跳转系统的设置界面
		// #ifdef APP-PLUS
		permision.gotoAppSetting();
		// #endif
	},
};
